import "./Type.scss"

const Type = memo(({ font, prefix, pause = 2 }: { font: string[], prefix: string, pause?: number }) => {
  const [showFont, setShowFont] = useState("")

  useEffect(() => {
    if (!font[0]) return;
    let index = 0
    let curIndex = 0
    let reverse = false
    let stop = false
    const timer = setInterval(() => {
      if (stop) return
      const curFont = font[index]
      const curfontLen = curFont.length
      // 1 随机加减
      let mathNum = Math.random()
      if (reverse) mathNum = mathNum > 0.5 ? -3 : -6
      else mathNum = mathNum > 0.5 ? 1 : 2
      // 2 判断当前字符索引加减
      curIndex = curIndex + mathNum
      if (curIndex < 0) curIndex = 0
      else if (curIndex > curfontLen) curIndex = curfontLen
      reverse ? setShowFont(curFont.substring(0, curIndex)) : setShowFont(curFont.substring(0, curIndex))
      // 3 判断翻转删除添加
      if (curIndex === curfontLen) {
        // 停顿两秒
        stop = true
        reverse = true
        setTimeout(() => {
          stop = false
        }, pause * 1000);
      } else if (curIndex === 0) {
        reverse = false
        // 判断数组是否有剩余值，输出
        index = font[index + 1] ? index + 1 : 0
      }
    }, 500)
    return () => clearInterval(timer)
  }, [font])

  return (
    <div className="type-com">
      <span className="type-font">{prefix}{showFont}</span>
    </div>
  )
})

export default Type
